<template>
	<view class="predetermineDetails" @click="clearCountdown">
		<view class="status_bar_h" :style="{
				height: `${statusBarHeight}px`,
				backgroundColor: '#20BF6C',
			}"></view>
		<view class="img_box">
			<!-- <swiper
				style="height: 400rpx"
				circular
				:indicator-dots="false"
				:autoplay="true"
				:interval="2000"
				:duration="500">
				<swiper-item
					v-for="(item, key) in src"
					:key="key">
					<view class=""
						><image
							style="width: 100%; height: 400rpx"
							mode="aspectFill"
							:src="item"></image
					></view>
				</swiper-item>
			</swiper> -->
			<image style="width: 100%; height: 400rpx" mode="aspectFill" :src="src">
			</image>
			<view class="back" @click="retreat">
				<image src="/static/images/arrow-left.png" mode="widthFix"></image>
				<text>返回</text>
			</view>
		</view>
		<view class="main">
			<view class="title">
				<view class="store">{{ view.store }}</view>
				<view class="info">
					<text>歡迎您：</text>
					<text>{{ view.user.mobile?view.user.mobile:view.user.user.mobile }}</text>
					|
					<!-- <text>{{
						typeof (view.user?.level * 1) === 'number'
							? `${view.user.level === 0 ? '普通會員 | ' : ''}`
							: ''
					}}</text> -->
					<text>
						{{ view.user.mobile?view.user.level === 0 ? '普通會員':'' : view.user.user.level === 0 ? '普通會員' : '' }}
					</text>
					|
					<!-- <text v-if="view.user?.mobile" @click="logout">退出</text> -->
					<text @click="logout">退出</text>
				</view>
			</view>
			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll_Y" @scrolltoupper="upper"
				@scrolltolower="lower" @scroll="scroll">
				<view class="room">
					<view class="room_box">
						<view class="room_base">
							<view style="display: flex;" class="">
								<view class="room_title">{{ view.base.name }}</view>
								<view class="room_state">
									{{ setRoomStatus(view.base.room_status) }}
								</view>
							</view>
							<view class="select-time" @click="showSelectTime=true">
								<view class="time">{{valueTime}}</view>
								<view class="xiala">
									<image src="/static/images/xiala.png" mode="widthFix"></image>
								</view>
							</view>
						</view>
						<u-datetime-picker @confirm="confirmTime" @close="showSelectTime=false"
							@cancel="showSelectTime=false" :closeOnClickOverlay="true" :minDate="minDate"
							v-model="value" confirmText="確定" :show="showSelectTime" mode="date"></u-datetime-picker>


						<view class="period_time">
							<view class="book_day">{{ bookDay }}</view>

							<view class="book_state box">
								<view style="display: flex;">
									<view class="bs" style="height: 30rpx;"
										v-for="(timeBarItem,timebarIndex) in timeBar" :key="timebarIndex"
										:style="{width:100/timeBar.length + '%' }">
										<view class="bs_deep"
											v-for="(orderTimeItem,orderIndex) in orderTimelot(timesLot)"
											:key="orderIndex">
											<view class="deep"
												:style="{width:setWidth(timeBarItem,orderTimeItem) + '%'}"
												v-if="timeBarItem>=orderTimeItem.start && timeBarItem<=orderTimeItem.end">
											</view>
										</view>
									</view>
								</view>
								<view class="item">
									<view :style="{width:100/timeBarText.length + '%' }"
										v-for="(item,index) in timeBarText" :key="index">
										<text>{{item==0?'次日':item}}</text>
									</view>
								</view>
							</view>
						</view>

						<view class="room_pack" v-if="view.package_list?view.package_list.length:null">
							<view style="" class="room_pack_title">
								<text>點選優惠套餐</text>
								<image src="@/static/images/jiantou_xiangxia.png" mode="widthFix"></image>
							</view>

							<view class="room_pack_list">
								<view class="room_pack_list_item"
									:class="{active:selectPackageInfo?selectPackageInfo.id==pack.id?true:false:false}"
									v-for="(pack, packKey) of view.package_list" :key="packKey"
									@click="roomPackselected(pack, packKey)">
									<view class="room_pack_list_time">{{
										`${pack.duration_hour}小時`
									}}</view>
									<view class="room_pack_list_time">{{
										`現價$${Math.floor(pack.price)}`
									}}</view>

								</view>
							</view>
						</view>


						<view class="time-box">
							<view class="time-start-box" @click="isStartTimeShow=true">
								<view class="">開始時間：</view>
								<view class="time-select">
									<text>{{view.startTime}}</text>
									<u-icon name="calendar" color="#39B19D" size="24"></u-icon>
								</view>
							</view>
							<view class="time-start-box" @click="openSelectDuration">
								<view class="">時長：</view>
								<view class="time-select" :class="{active:selectPackageInfo}">
									<text>{{view.durationText}}</text>
									<u-icon name="calendar" :color="selectPackageInfo?'#ccc':'#39B19D'"
										size="24"></u-icon>
								</view>
							</view>
						</view>

						<view class="ticket_box">
							<u-cell-group>
								<u-cell title="訂單金額" :isLink="false" :value="`${form.price ? form.price : 0}`"></u-cell>
								<u-cell title="-會員折扣" :isLink="false"
									:value="`${view.score ? view.score : 0} 折`"></u-cell>
								<!-- <u-cell
									title="-电子票券"
									:value="`${view.ticket ? view.ticket : '选择电子票券'}`"
									@click="isTicketsShow = true"
									:isLink="true"></u-cell> -->
								<!-- <u-cell title="-優惠卷" :value="`${view.coupon ? view.coupon : '选择優惠卷'}`"
									@click="isCouponShow = true" :isLink="true"></u-cell> -->
								<u-cell title="-優惠卷" :value="`${selectCouponInfo?selectCouponInfo.title : '選擇優惠卷'}`"
									@click="isCouponShow = true" :isLink="true"></u-cell>
								<!-- <u-cell title="-賬戶余額" :isLink="false"
									:value="`${view.balance ? view.balance : 0}`"></u-cell> -->
								<u-cell title="-支付金額" :isLink="false"
									:value="`${form.money ? form.money : 0}`"></u-cell>
							</u-cell-group>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="footer">
			<view class="btn_box">
				<view class="container">
					<up-button class="bth" color="#39B19D" :disabled="payDisabled" @click="toPay">
						選擇繳費方式
					</up-button>
				</view>
			</view>
		</view>
		<view class="feature">
			<!-- 日期選擇 -->
			<u-datetime-picker confirmText="確認" mode="time" @confirm="setStartTimeConfirm"
				@cancel="isStartTimeShow = false" :show="isStartTimeShow" v-model="form.startTime"></u-datetime-picker>
			<!-- 時長 -->
			<u-picker confirmText="確認" @confirm="setDurationConfirm" @cancel="isDurationShow = false"
				:show="isDurationShow" :columns="options.duration" keyName="value2"></u-picker>
			<u-popup :show="isTicketsShow" bgColor="#f8f8f8" :round="10" mode="bottom" :closeable="true" @close="close">
				<custom-tickets style="height: 500rpx; padding-top: 60rpx" :list="options.ticket"
					@ticketSlected="ticketSlected">
				</custom-tickets>
			</u-popup>
			<!-- 優惠價功能 -->
			<u-popup :show="isCouponShow" bgColor="#f8f8f8" :round="10" mode="bottom" :closeable="true" @close="close">
				<custom-coupon style="height: 500rpx; padding-top: 60rpx" :list="options.coupon" @slected="slected">
				</custom-coupon>
			</u-popup>
			<!-- 支付功能 -->
			<u-popup :show="isPayShow" bgColor="#fff" :round="10" mode="bottom" :closeable="true" @close="close">
				<custom-pay :payPrice="form.money" @paymentBalance="paymentBalance"
					style="height: 500rpx; padding-top: 60rpx" :payType="payType" @confirm="confirm" @close="close"
					@slectedPay="slectedPay">
				</custom-pay>
			</u-popup>
			<!-- 餘額支付完成 -->
			<u-popup mode="center" round="10" :show="showPayFinish">
				<view class="pay_finish">
					<view class="price">${{form.money}}</view>
					<view class="order_no">訂單編號：{{orderNo}}</view>
					<view class="order_no">交易方式：餘額支付</view>
					<view class="back" @click="back">返回</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import useStore from '@/store/index.js';
	import baseURL from '@/utils/baseURL.js';
	import {
		getCouponList,
		getRoomDetails,
		getUserCoupon
	} from '@/api/user';
	import {
		getUserStoreInfo
	} from '@/api/store';
	import CustomTickets from './components/CustomTickets';
	import CustomCoupon from './components/CustomCoupon';
	import CustomPay from './components/CustomPay';
	import {
		formatDate,
		format
	} from '@/utils/formatDate';
	import {
		countDate
	} from '@/utils/countDate';
	import {
		countDurationDate
	} from '@/utils/countDurationDate';
	import {
		durationList
	} from '@/config/duration';

	import dayjs from 'dayjs'

	import {
		getOrderCode,
		getOrderList
	} from '@/api/order.js'

	export default {
		components: {
			CustomTickets,
			CustomCoupon,
			CustomPay
		},
		data() {
			return {
				minHour: '',
				minMinute: '',
				src: [],
				baseURL,
				isChecked: false,
				isDurationDis: false,
				payDisabled: false,
				isStartTimeShow: false,
				isEndTimeShow: false,
				isDurationShow: false,
				isTicketsShow: false,
				isCouponShow: false,
				isPayShow: false,
				constBase: {
					price: 0,
				}, // 基础常量信息
				form: {
					startTime: '',
					endTime: '',
					duration: '',
					price: '',
					money: 0,
					date: 0, // 预约日期
					wek: 0, // 预约日期
					year: 0, // 预约日期
					coupon_id: 0,
					package_id: 0, // 套餐id

				},
				view: {
					base: {},
					room: '',
					roomId: '',
					ticket: '',
					user: {},
					store: '',
					coupon: '',
					duration: '',
					durationText: '',
					startTime: '',
					endTime: '',
					package_list: [], // 套餐列表
					shop: {
						nums: '',
						price: '',
						score: '',
					}, // 套餐情况
					balance: '0', // 账户余额
					price: 0, // 订单金额
					score: '0', // 会员折扣
					totalAmount: '0', // 支付金额
				},
				statusBarHeight: 0, // 顶部状态栏高度
				bthHeight: 0, // 底部按钮高度
				options: {
					// duration: durationList,
					duration: [],
					ticket: [],
					coupon: [],
					day: [],
				},
				timeStampList: [],
				num_time_stamp: [],
				room_times_color: [],
				num_time: [],
				shopCount: 1, // 购买数量
				scrollTop: 0,
				bookDay: '', // 当前时间
				checkTimeCount: 0, // 选择的时间
				old: {
					scrollTop: 0,
				},
				payType: 1,
				packSelectedCount: -1, // 套餐默认不选择
				page: 1,
				timer: null,
				showSelectTime: false,
				value: Date.now(),
				minDate: new Date().getTime(),
				valueTime: '',
				selectPackageInfo: null,
				userLevel: 0, // 0--不享受折扣   1--可享受折扣
				selectCouponInfo: null,
				sumPrice: '',
				showPayFinish: false,
				orderNo: '',
				payflag: true,
				backTimer: null,

				// 时间展示条
				timeBar: [], // 存放当前时间之后的24小时
				timeBarText: [], // 存放时间文本
				timesLot: [],
			};
		},
		onLoad() {
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
			const screenTop = uni.getSystemInfoSync().safeArea.top;
			const screenBot = uni.getSystemInfoSync().safeArea.bottom;
			this.bthHeight = uni.getSystemInfoSync().screenHeight - (1000 - 40) / 2;
			const {
				user
			} = useStore();
			const userOptions = JSON.parse(uni.getStorageSync('userOptions'));
			const equipmentOptions = JSON.parse(uni.getStorageSync('equipmentOptions'));
			this.view = {
				base: {
					...user.ticket
				},
				roomId: user.ticket.id,
				ticket: '',
				user: userOptions,
				store: equipmentOptions.name,
				coupon: '',
				score: equipmentOptions.vip_rate,
			};
			// console.log(this.view, '1111111')
			this.form = {};

			this.setDuration()

			this.getCouponList();
			this.getTickectsList();
			this.setSwiperImg();
			this.setDayList();
			this.getRoomDetails();
			this.countdown();
			this.getUserStoreInfo();
			this.setReservationTime();
			// 	charging_min_time: '0',
			// 获取当前时间
			this.getTimeNow()
			this.setValueTime()

			// 獲取優惠券列表
			// this.getUserCouponFn()

			this.setStastTime()

			this.setTimeBar()
		},
		onUnload() {
			clearTimeout(this.timer);
			clearTimeout(this.backTimer)
		},
		onShow() {
			this.computedMoney()
		},
		methods: {
			setTimeBar() {
				// 获取当前时间的时间戳
				let now = new Date().getTime()
				let end = now + 3600000 * 24
				for (var i = now; i <= end; i += 1800000) {
					this.timeBar.push(i)
				}
				for (var j = now; j <= end; j += 3600000) {
					this.timeBarText.push(this.setTimeHours(j))
				}
			},
			setTimeHours(num) {
				return new Date(num).getHours()
			},
			orderTimelot(arr) {
				if (!arr.length) return []
				let a = []
				arr.forEach(item => {
					a.push({
						start: item.start * 1000,
						end: item.end * 1000
					})
				})
				return a
			},
			setWidth(time, item) {
				return item.end / time * 100
				// console.log(item.end / time)
				// return 100
			},
			confirm() {
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				// this.form.money =
				// 	equipmentOptions.vip_rate !== 0 ?
				// 	(this.form.price * 1000 -
				// 		this.form.price * (equipmentOptions.vip_rate / 10) * 1000) /
				// 	1000 :
				// 	this.form.price;
				const {
					order
				} = useStore();
				order.setOrderObjState({
					...this.form
				});
				console.log('order', order.getOrderObj);
			},
			countdown() {
				const currentTime = Date.now();
				const {
					times
				} = useStore();
				// if (currentTime - times.getLastTimes()) {
				// }
				// console.log('times.getLastTimes()', times.getTimeout);
				this.timer = setTimeout(() => {
					// uni.navigateTo({
					// 	url: '/pages/index/index',
					// });
				}, 1000 * 60 * 10);
			},
			clearCountdown() {
				clearTimeout(this.timer);
				this.countdown();
			},
			setSwiperImg() {
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				// console.log('equipmentOptions', equipmentOptions.imagejh);
				// const _src = equipmentOptions.imagejh ?
				// 	equipmentOptions.imagejh.split(',') : [];
				// if (_src.length > 1) {
				// 	this.src = _src.map(item => baseURL + item);
				// } else if (_src.length === 1) {
				// 	this.src = [baseURL + _src[0]];
				// }

				this.src = baseURL + equipmentOptions.image4
			},
			setReservationTime() {
				// 設置預約時間段總時長（根據店鋪營業時間）
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				let startTime = Number(equipmentOptions.open.split(':')[0]);
				let endTime = this.store_config ?
					Number(equipmentOptions.close.split(':')[0]) -
					Number(equipmentOptions.store_config.order_end_time.split(':')[0]) :
					Number(equipmentOptions.close.split(':')[0]);

				// 將營業時間轉換成時間戳
				let startTimeStamp = startTime * 60 * 60 * 1000;
				let endTimeStamp = endTime * 60 * 60 * 1000;

				if (this.store_config) {
					// 按照店鋪配置的時間表間隔
					let h = Number(this.store_config.schedule_interval.split(':')[0]);
					// let h = 0
					let m = Number(this.store_config.schedule_interval.split(':')[1]);
					// 時間表間隔時間戳
					let timeStamp = h * 60 * 60 * 1000 + m * 60 * 1000;
					let arr = [];
					for (var i = startTimeStamp; i <= endTimeStamp; i += timeStamp) {
						arr.push(i);
					}
					this.timeStampList = [...arr];
					let hour = '';
					let min = '';
					arr.forEach(item => {
						hour = Math.floor(item / 1000 / 60 / 60);
						min = Math.floor((item % (1000 * 60 * 60)) / (1000 * 60));
						min = min > 10 ? min : '0' + min;
						this.num_time.push(hour + ':' + min);
					});

					let arrColor = [];
					this.colorDeep.forEach(item => {
						arrColor.push({
							start: item.start * 60 * 60 * 1000,
							end: item.end * 60 * 60 * 1000,
						});
					});
					this.colorDeepStamp = [...arrColor];
				} else {
					// 當營業時間不超過24點的時候
					// if (endTime < 24) {
					// 	for (var i = startTime; i <= endTime; i++) {
					// 		this.num_time.push(i);
					// 	}
					// }

					// 當營業時間是超過24點，即開到凌晨或者24小時營業的時候
					if (endTime <= startTime) {
						for (var i = startTime; i <= endTime + 24; i++) {
							if (i < 24) {
								this.num_time.push(i);
							} else if (i == 24) {
								this.num_time.push('次日');
							} else {
								this.num_time.push(i - 24);
							}
						}
					}

					// console.log(this.num_time, '查看')
				}
			},
			roomTimeStamp(arr) {
				let a = arr.map(item => {
					let startH = new Date(item.start * 1000).getHours();
					let startM = new Date(item.start * 1000).getMinutes();
					let endH = new Date(item.end * 1000).getHours();
					let endM = new Date(item.end * 1000).getMinutes();
					return {
						start: startH + ':' + startM,
						end: endH + ':' + endM,
					};
				});

				let b = a.map(item => {
					if (this.hourMinStamp(item.start) >= this.hourMinStamp(item.end)) {
						return {
							start: this.hourMinStamp(item.start),
							end: this.hourMinStamp(item.end) + 24 * 60 * 60 * 1000,
						};
					} else {
						return {
							start: this.hourMinStamp(item.start),
							end: this.hourMinStamp(item.end),
						};
					}

				});

				this.room_times_color = [...b];
			},
			numTimeStamp(arr) {
				let a = arr.indexOf('次日');
				let arrStamp = arr.map((item, index) => {
					if (a !== -1) {
						if (index > a) {
							return item * 60 * 60 * 1000 + 24 * 60 * 60 * 1000;
						} else if (index == a) {
							return 24 * 60 * 60 * 1000;
						} else {
							return item * 60 * 60 * 1000;
						}
					} else {
						return item * 60 * 60 * 1000;
					}
				});
				this.num_time_stamp = [...arrStamp];
			},
			cut(time, type) {
				time = time.toString();
				if (time.indexOf(':') !== -1) {
					if (type == 'hour') {
						return time.split(':')[0];
					} else if (type == 'minute') {
						return time.split(':')[1];
					}
				} else {
					if (type == 'hour') {
						return time;
					} else if (type == 'minute') {
						return '';
					}
				}
			},
			setDayList() {
				let arr = [];
				for (let i = 0; i < 7; i++) {
					arr.push({
						day: format(Date.now() + 1000 * 60 * 60 * 24 * i, 'MM-dd'),
						wek: format(Date.now() + 1000 * 60 * 60 * 24 * i, 'w'),
					});
				}
				this.form.year = new Date().getFullYear();
				this.form.date = arr[0].day;
				this.form.wek = arr[0].wek;
				this.options.day = arr;
			},
			slectedDate(day, index) {
				this.checkTimeCount = index;
				this.form.date = day.day;
				this.form.wek = day.wek;
				console.log('this.form.date', this.form.date);
			},
			getTickectsList() {
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				getCouponList({
					type: 2,
					page: this.page,
					store_id: equipmentOptions.id,
				}).then(res => {
					this.options.ticket = res;
				});
			},
			getCouponList() {
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				getCouponList({
					type: 1,
					page: this.page,
					store_id: equipmentOptions.id,
				}).then(res => {
					this.options.coupon = res;
				});
			},
			getRoomDetails(date) {
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				const {
					user
				} = useStore();
				const room_id = user.ticket.id;
				const _date = date ? date : {};
				getRoomDetails({
					room_id: room_id,
					..._date
				}).then(res => {
					this.view.package_list = res.package_list;
					this.view.shop = res;
					this.constBase.price = res.price;
					this.view.price =
						(res.price * 1000 -
							res.price * (equipmentOptions.vip_rate / 10) * 1000) /
						1000;
					// this.form.price =
					// 	(res.price * 1000 -
					// 		res.price * (equipmentOptions.vip_rate / 10) * 1000) /
					// 	1000;
					this.form.price = Number(res.price).toFixed(0);
					// console.log('res.price', this.form.price);
					this.form.money =
						Number(equipmentOptions.vip_rate !== 0 ?
							(res.price * 1000 -
								res.price * (equipmentOptions.vip_rate / 10) * 1000) /
							1000 :
							res.price).toFixed(0);
					this.sumPrice = this.form.money
					this.view.timeList = res.times_arr;
					this.numTimeStamp(this.num_time);
					this.roomTimeStamp(res.times_arr);
					this.timesLot = res.times_arr
				});
			},
			setRoomStatus(status) {
				switch (status) {
					case 0:
						return '空閒中';
					case 1:
						return '使用中';
					case 2:
						return '待打掃';
					case 3:
						return '打掃中';
					case 4:
						return '';
					case 5:
						return '已下架'
				}
			},
			hourMinStamp(time) {
				let h = Number(time.split(':')[0]) * 60 * 60 * 1000;
				let m = Number(time.split(':')[1]) * 60 * 1000;
				return h + m;
			},
			getRoomList() {
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				uni.request({
					url: baseURL + '/api/index/getRoom',
					data: {
						store_id: equipmentOptions.data.data.store_id,
						page: this.page,
					},
					header: {
						Accept: 'application/json',
						'Content-Type': 'application/json',
						'X-Requested-With': 'XMLHttpRequest',
					},
					method: 'GET',
					sslVerify: false,
					success: res => {
						this.list = res.data.data.room;
					},
					fail: error => {},
				});
			},

			getUserStoreInfo() {
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				const store_id = equipmentOptions.data.data.store_id;
				getUserStoreInfo({
					store_id
				}).then(res => {
					this.view.balance = res.balance;
					this.userLevel = res.user_level
					console.log(res, '用戶信息')
				});
			},
			handPackCount(data) {
				let count = this.shopCount;
				let price = this.constBase.price; // 常量信息
				let totalPrice = this.view.price;
				console.log('price前', price);
				if (data === 'reduce') {
					if (count > 1) {
						count -= 1;
					} else {
						count = 1;
					}
				} else if (data === 'add') {
					count += 1;
				}
				this.shopCount = count;
				this.form.price = (price * 1000 * count) / 1000;
				this.form.money = Number((totalPrice * 1000 * count) / 1000).toFixed(0);
			},
			ticketSlected(data) {
				this.view.ticket = data.title;
				this.view.ticketMoney = data.money * 1;
				this.close();
			},
			setStartTimeConfirm(e) {
				this.view.startTime = e.value;
				this.form.startTime = e.value;
				if (this.view.duration) {
					this.view.endTime = countDate(
						this.view.startTime,
						this.form.duration[0]
					);
					this.form.endTime = countDate(
						this.view.startTime,
						this.form.duration[0]
					);
					this.view.endTime = countDate(this.view.startTime, this.form.duration);
					this.form.endTime = countDate(this.view.startTime, this.form.duration);
				}
				this.isStartTimeShow = false;
				this.isDurationDis = true;


				if (this.selectPackageInfo) {
					this.setEndTime(this.selectPackageInfo.duration_hour)
					return
				} else {
					this.setEndTime()
				}

				const _equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				this.computedPriceByDuration(this.view.duration, this.form.price, _equipmentOptions.store_config)
			},
			// 设置时长
			setDurationConfirm(e) {
				this.view.duration = e.value[0].value1;
				this.view.durationText = e.value[0].value1;
				this.form.duration = e.value[0].value1;

				// this.view.endTime = this.view.startTime + this.view.duration;
				const _equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				// this.form.endTime = this.form.startTime + this.form.duration;

				this.view.endTime = countDate(this.view.startTime, e.value[0].value1);
				this.form.endTime = countDate(this.view.startTime, e.value[0].value1);
				this.form.money = countDurationDate(
					_equipmentOptions.store_config.charging_min_time,
					e.value[0].value1
				);
				this.selectCouponInfo = null
				this.isDurationShow = false;
				this.computedPriceByDuration(e.value[0].value1, this.form.price, _equipmentOptions.store_config)
				this.setEndTime()
			},
			slected(data) {
				// this.form.coupon_id = data.id;
				// this.view.coupon = data.title;
				// this.view.couponMoney = data.money * 1000;
				// // this.form.price = (this.view.price * 1000 - data.money * 1000) / 1000;
				// this.form.money = (this.view.price * 1000 - data.money * 1000) / 1000;
				// this.close();
				// const {
				// 	order
				// } = useStore();
				// const _id = data.id;
				// order.setOrderCouponIdState(_id);
				// console.log(data, this.selectCouponInfo, this.form.money)
				this.form.money = this.sumPrice
				if (this.form.money >= Number(data.min)) {
					// 滿足優惠券使用條件
					if (this.selectCouponInfo && this.selectCouponInfo.id !== data.id) {
						this.selectCouponInfo = data
						this.close();
					} else if (this.selectCouponInfo && this.selectCouponInfo == data.id) {
						this.selectCouponInfo = null
					} else {
						this.selectCouponInfo = data
						this.close();
					}
					this.form.money = this.selectCouponInfo ? this.sumPrice - Number(this.selectCouponInfo.money) : this
						.sumPrice
				} else {
					uni.showToast({
						title: '該優惠券不滿足使用條件',
						icon: 'none'
					})
				}

				const {
					order
				} = useStore()

				order.setCouponInfo(this.selectCouponInfo)

			},
			slectedPay(index) {
				// console.log('dsjfksdjfkjsdfkj', index);
				this.form.pay_type = index;
				this.payType = index;
				const {
					order
				} = useStore();
				const _obj = {
					pay_type: index
				};
				order.setOrderPayState(_obj);
				// this.close();
			},
			close() {
				this.isCouponShow = false;
				this.isTicketsShow = false;
				this.isPayShow = false;
			},
			formatDate(data) {
				return formatDate(data);
			},
			format(data) {
				return format(data);
			},
			jump(data) {
				let url = '';
				switch (data) {
					case 'register':
						url = '/pages/register/register';
						break;
					case 'codeLogin':
						url = '/pages/menu/menu';
						break;
					case 'scanCode':
						url = '/pages/scanCode/scanCode';
						break;
					case 'pay':
						url = '/pages/pay/ticket/ticket';
						break;
					case 'logout':
						url = '/pages/index/index';
						break;
					default:
				}
				uni.navigateTo({
					url
				});
			},
			toPay() {
				this.payDisabled = false;
				const {
					user,
					order
				} = useStore();
				const room_id = user.ticket.id;
				const {
					package_id
				} = this.form;
				// if (this.checkForm()) {
				this.isPayShow = true;
				// 订单详情
				order.setOrderObjState({
					...this.form
				});
				console.log(this.form, '訂單詳情')
				//  支付
				// console.log('支付');
				// }
			},
			checkForm() {
				const {
					startTime,
					endTime
				} = this.form;
				return startTime && endTime;
			},
			// 套餐
			roomPackselected(data, index) {
				// console.log('e', data, 'index', index);
				// this.packSelectedCount = index;
				// this.form.package_id = data.id;
				// const hy = (data.price * 1000 * this.view.score) / 10 / 1000;
				// this.form.package_options = {
				// 	...data,
				// 	hy
				// };
				if (this.selectPackageInfo) {
					if (this.selectPackageInfo.id == data.id) {
						this.selectPackageInfo = null
					} else {
						this.selectPackageInfo = data
					}
				} else {
					this.selectPackageInfo = data
				}

				this.selectCouponInfo = null

				if (this.selectPackageInfo) {
					this.form.money = this.selectPackageInfo.price
					this.sumPrice = this.selectPackageInfo.price
					this.view.duration = ''
				} else {
					this.form.money = 0
					this.sumPrice = 0
				}

				const {
					order
				} = useStore()
				// console.log(order,'查看111111111')
				order.setPackage(this.selectPackageInfo)

				if (this.selectPackageInfo) {
					this.setEndTime(this.selectPackageInfo.duration_hour)
				} else {
					this.form.endTime = ''
				}
			},
			handPrePage() {
				if (this.page !== 1) {
					this.page -= 1;
					this.preDisabled = false;
					this.getRoomList();
				} else if (this.page <= 1) {
					this.preDisabled = true;
				}
			},
			handNextPage() {
				this.page += 1;
				this.preDisabled = false;
				this.getRoomList();
			},
			handShopping(data) {
				const {
					user
				} = useStore();
				user.setTicketState(data);
				this.jump('pay');
			},
			logout() {
				uni.removeStorageSync('userOptions');
				this.jump('logout');
			},
			upper(e) {},
			lower(e) {},
			scroll(e) {},
			// 获取当前日期时间
			getTimeNow() {
				const now = new Date();
				const hours = now.getHours().toString().padStart(2, '0');
				const minutes = now.getMinutes().toString().padStart(2, '0');
				const currentTime = `${hours}:${minutes}`;
				// 获取当前小时时间戳
				const timestamp = now.getHours();
				const timeminut = now.getMinutes()
				console.log(currentTime);
				this.view.startTime = currentTime
				this.minHour = timestamp
				this.minMinute = timeminut
			},
			//设置选择日期最小值

			confirmTime(e) {
				// console.log(e.value)
				let time = new Date(e.value)
				let y = time.getFullYear()
				let m = time.getMonth() + 1 >= 10 ? time.getMonth() + 1 : '0' + (time.getMonth() + 1)
				let d = time.getDate() >= 10 ? time.getDate() : '0' + time.getDate()
				this.valueTime = y + '-' + m + '-' + d
				this.showSelectTime = false
				this.retrieveRoomDetails(this.valueTime)
				const {
					order
				} = useStore()
				order.setDate(this.valueTime)
			},
			setValueTime() {
				let time = new Date()
				let y = time.getFullYear()
				let m = time.getMonth() + 1 >= 10 ? time.getMonth() + 1 : '0' + (time.getMonth() + 1)
				let d = time.getDate() >= 10 ? time.getDate() : '0' + time.getDate()
				this.valueTime = y + '-' + m + '-' + d
				const {
					order
				} = useStore()
				order.setDate(this.valueTime)
			},
			retrieveRoomDetails(date) {
				const {
					user
				} = useStore();
				const room_id = user.ticket.id;
				getRoomDetails({
					room_id,
					date
				}).then(res => {
					// console.log(res)
					this.numTimeStamp(this.num_time);
					this.roomTimeStamp(res.times_arr);
					this.timesLot = res.times_arr
				})
			},
			openSelectDuration() {
				if (this.selectPackageInfo) {
					uni.showToast({
						title: '當前已選擇了套餐',
						icon: 'none'
					})
				} else {
					this.isDurationShow = true
				}
			},
			computedPriceByDuration(duration, price, config) {
				if (!duration) return
				if (!duration && this.selectPackageInfo) {
					duration = this.selectPackageInfo.duration_hour + ':' + '0'
				}
				const equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				if (this.userLevel) {
					if (equipmentOptions.vip_rate) {
						price = price * equipmentOptions.vip_rate / 10
					}
				}

				let h = Number(duration.split(':')[0])
				let m = Number(duration.split(':')[1])
				if (config) {
					let minChargingDuration = config.charging_min_time
					// 最小計費時長的價格
					let minPrice = (price / (60 / minChargingDuration)).toFixed(2)

					let n = Math.ceil(m / minChargingDuration)

					let sumPrice = h * price + n * minPrice
					this.form.money = sumPrice
					this.sumPrice = sumPrice
				} else {
					let minPrice = (price / (60 / 1)).toFixed(2)

					let n = Math.ceil(m / minChargingDuration)

					let sumPrice = h * price + n * minPrice
					this.form.money = sumPrice
					this.sumPrice = sumPrice
				}
			},
			getUserCouponFn() {
				const {
					user
				} = useStore();
				const room_id = user.ticket.id;
				getUserCoupon({
					room_id
				}).then(res => {
					// console.log(res,'優惠券列表')
					this.options.coupon = [...res]
					console.log(this.options.coupon, '優惠券')
				})
			},
			setStastTime() {
				let a = dayjs().hour() * 60 * 60 * 1000 + (dayjs().minute() + 5) * 60 * 1000
				let h = Math.floor(a / 60 / 60 / 1000)
				let m = Math.floor((a % (60 * 60 * 1000)) / 60 / 1000)
				this.view.startTime = this.montage(h) + ':' + this.montage(m)
				this.form.startTime = this.view.startTime
			},
			montage(num) {
				return num < 10 ? '0' + num : num
			},
			computedMoney() {
				const _equipmentOptions = JSON.parse(
					uni.getStorageSync('equipmentOptions')
				);
				this.computedPriceByDuration(this.view.duration, this.form.price, _equipmentOptions.store_config)
				// console.log(this.form, '查看')
			},
			setEndTime(packageH) {
				if (!packageH) {
					if (this.view.duration.indexOf(':') == -1) return
					let sH = Number(this.view.startTime.split(':')[0])
					let sM = Number(this.view.startTime.split(':')[1])
					let dH = Number(this.view.duration.split(':')[0])
					let dM = Number(this.view.duration.split(':')[1])
					let eT = (sH + dH) * 60 * 60 * 1000 + (sM + dM) * 60 * 1000
					let eH = Math.floor(eT / 60 / 60 / 1000)
					let eM = Math.floor((eT % (60 * 60 * 1000)) / 60 / 1000)

					eH = eH >= 24 ? eH - 24 : eH

					this.form.endTime = eH + ':' + eM
				} else {
					let sH = Number(this.view.startTime.split(':')[0])
					let sM = Number(this.view.startTime.split(':')[1])
					let dH = Number(packageH)
					// let dM = Number(this.view.duration.split(':')[1])
					let eT = (sH + dH) * 60 * 60 * 1000 + (sM) * 60 * 1000
					let eH = Math.floor(eT / 60 / 60 / 1000)
					let eM = Math.floor((eT % (60 * 60 * 1000)) / 60 / 1000)

					eH = eH >= 24 ? eH - 24 : eH

					this.form.endTime = eH + ':' + eM
				}

			},
			paymentBalance() {
				const {
					pay_type,
					money,
					year,
					date,
					endTime,
					startTime
				} = this.form
				const {
					roomId: room_id
				} = this.view
				const params = {
					room_id,
					pay_type: Number(pay_type),
					money,
					// date: year + '-' + date,
					date: this.valueTime,
					timeslot: startTime + ',' + endTime,
					package_id: this.selectPackageInfo ? this.selectPackageInfo.id : '',
					coupon_id: this.selectCouponInfo ? this.selectCouponInfo.id : ''
				}

				if (!this.payflag) return

				getOrderCode(params).then(res => {
					this.isPayShow = false
					// console.log(res, '支付成功')
					this.orderNo = res.order_no

					if (res.code == 0) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
						this.payflag = true
						return
					}
					this.payflag = false

					uni.showToast({
						title: '支付成功',
						icon: 'success',
						duration: 2000
					})
					setTimeout(() => {
						this.showPayFinish = true
					}, 2000)

					this.backTimer = setTimeout(() => {
						this.showPayFinish = false
						this.back()
					}, 15000)
				})
			},
			back() {
				clearTimeout(this.backTimer)
				this.showPayFinish = false
				// this.jump('logout');
				getOrderList({
					page: 1
				}).then(res => {
					let obj = res.filter(item => item.order_no == this.orderNo)[0]
					uni.reLaunch({
						url: `/pages/order/order_details?id=${obj.id}`
					})
				})

				// uni.reLaunch({
				// 	url: '/pages/order/order'
				// })
			},
			retreat() {
				uni.reLaunch({
					url: '/pages/predetermine/predetermine'
				})
			},
			setDuration() {
				let arr = []
				for (var i = 1; i <= 24; i++) {
					arr.push({
						value1: i + ':00',
						value2: i + '小時'
					})
				}
				this.options.duration = [
					[...arr]
				]
			},
		},
	};
</script>

<style lang="scss" scoped>
	.predetermineDetails {
		height: 100%;

		.img_box {
			// padding: 40rpx 40rpx 0;
			position: relative;

			.back {
				position: fixed;
				left: 10rpx;
				bottom: 30rpx;
				display: flex;
				align-items: center;
				color: #fff;
				background-color: #ff914d;
				padding: 5rpx 10rpx;
				border-radius: 20rpx;
				z-index: 11;

				image {
					width: 50rpx;
					margin-right: 10rpx;
				}
			}
		}

		.main {
			padding: 0rpx 0 160rpx 0;
			font-size: 24rpx;
			color: $uni-color-green;

			.title {
				padding: 20rpx;
				font-size: 24rpx;
				color: $uni-color-green;
				display: flex;
				justify-content: space-between;
			}

			.scroll_Y {
				width: 100%; // 滚动区域的宽度
				height: 50vh; // 滚动区域的高度，为了兼容问题，尽量设置大一些
				background-color: $uni-color-white;

				.room {
					padding: 20rpx;

					&_box {
						height: 50rpx;

						.period_time {
							padding: 0 11rpx;

							.book_day {
								font-size: 17rpx;
								margin-bottom: 15rpx;
							}

							.deep {
								background: #39B19D;
								height: 30rpx;
							}

							.item {
								display: flex;
								font-size: 17rpx;
								text-align: center;

								view {
									display: flex;
									justify-content: center;
									flex-direction: column;
								}
							}

							.book_state {
								padding: 0 11rpx;

								.bs {
									border: 1rpx solid #707070;
									border-right: none;
									position: relative;

									&:last-child {
										border-right: 1rpx solid #707070;
									}

									&:nth-child(2n) {
										border-left: none;

										&::before {
											content: '';
											width: 1rpx;
											height: 50%;
											display: block;
											position: absolute;
											background-color: #FA533D;
											left: 0%;
											bottom: 0%;
											z-index: 2;
										}
									}

									.bs_deep {
										position: relative;
									}

									.deep {
										background: #39B19D;
										height: 30rpx;
										// width: 30rpx;
										width: 100%;
										position: absolute;
										z-index: 1;
									}
								}

								.item {
									display: flex;
									font-size: 17rpx;
									// text-align: center;

									view {
										display: flex;
										justify-content: center;
										flex-direction: column;
									}
								}
							}
						}

						.room_base {
							display: flex;
							justify-content: space-between;
							align-content: center;

							.room_title {
								line-height: 40rpx;
							}

							.room_state {
								width: 100rpx;
								height: 40rpx;
								margin-left: 20rpx;
								text-align: center;
								line-height: 40rpx;
								border-radius: 10rpx;
								color: $uni-color-white;
								background-color: $uni-color-green;
							}

							.select-time {
								display: flex;
								align-items: center;

								.time {
									font-size: 26rpx;
								}

								.xiala {
									image {
										width: 50rpx;
									}
								}
							}
						}

						.room_time {
							margin-top: 20rpx;
							width: 100%;
							display: flex;
							justify-content: space-between;

							&_list {
								// width: 100rpx;
								padding: 10rpx;
								border: 2rpx solid $uni-color-green;
								border-radius: 10rpx;
								text-align: center;
							}

							.checked {
								background-color: $uni-color-green-light;
							}
						}

						.room_pack {
							// min-height: 150rpx;
							max-height: 220rpx;
							// margin-top: 20rpx;
							overflow-y: scroll;

							&_list {
								margin-bottom: 10rpx;
								// background-color: #ff914d;
								color: #000;
								// text-align: center;
								display: flex;
								justify-content: space-between;

								// height: 100rpx;
								// overflow: hidden;
								&_time {
									// height: 30rpx;
									flex-grow: 1;
									text-align: center;
								}
							}
						}

						.select_time {
							display: flex;
							justify-content: space-between;

							&_box {
								flex: 1;
								padding: 0 20rpx;
								display: flex;
								flex-direction: column;
								justify-content: space-between;

								.select_time_title {
									height: 50rpx;
									text-align: center;
									line-height: 50rpx;
								}

								.select_time_content {
									flex: 1;
									display: flex;
									justify-content: space-between;
									border: 2rpx solid #dadbde;
									border-radius: 6rpx;

									.select_input {
										height: 80rpx;
										// padding: 26rpx 24rpx 24rpx;
										padding-left: 20rpx;
										text-align: left;
										line-height: 80rpx;
										box-sizing: border-box;
									}

									.select_icon {
										width: 40rpx;
										padding-right: 20rpx;
										display: flex;
										align-content: center;
									}
								}
							}
						}
					}
				}

				.current_duration {
					padding: 20rpx 0;

					.current_list {
						&_box {
							.period_time {
								padding: 0 11rpx;

								.book_day {
									font-size: 17rpx;
									margin-bottom: 15rpx;
								}

								.bs_deep {
									position: relative;
								}

								.deep {
									background: #39B19D;
									height: 30rpx;
									// width: 30rpx;
									width: 100%;
									position: absolute;
								}

								.item {
									display: flex;
									font-size: 17rpx;
									text-align: center;

									view {
										display: flex;
										justify-content: center;
										flex-direction: column;
									}
								}

								.book_state {
									padding: 0 11rpx;

									.bs {
										border: 1rpx solid #707070;
										border-right: none;
										position: relative;

										&:last-child {
											border-right: 1rpx solid #707070;
										}

										&:nth-child(2n) {
											border-left: none;

											&::before {
												content: '';
												width: 1rpx;
												height: 50%;
												display: block;
												position: absolute;
												background-color: #FA533D;
												left: 0%;
												bottom: 0%;
												z-index: 2;
											}
										}

										.bs_deep {
											position: relative;
										}

										.deep {
											background: #39B19D;
											height: 30rpx;
											// width: 30rpx;
											width: 100%;
											position: absolute;
											z-index: 1;
										}
									}

									.item {
										display: flex;
										font-size: 17rpx;
										// text-align: center;

										view {
											display: flex;
											justify-content: center;
											flex-direction: column;
										}
									}
								}
							}
						}
					}
				}

				.ticket_box {
					position: relative;
					margin-bottom: 20rpx;
					border-radius: 20rpx;
					background-color: $uni-color-white;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.left {
						width: 250rpx;
						height: 150rpx;
						text-align: center;
						border-top-left-radius: 20rpx;
						border-bottom-left-radius: 20rpx;
						display: flex;
						flex-direction: column;
						justify-content: center;
						color: $uni-color-white;
						mask-image: radial-gradient(circle at 500rpx 8rpx,
								transparent 8rpx,
								$uni-color-green 9rpx),
							radial-gradient(closest-side circle at 50%,
								$uni-color-green 99%,
								transparent 100%);
						mask-size: 100%, 10rpx 20rpx;
						mask-repeat: repeat, repeat-y;
						mask-position: 140rpx 10rpx, 245rpx;
						mask-composite: source-out;
						mask-composite: subtract;
						background-color: $uni-color-green;
					}

					.right {
						flex: 1;
						height: 150rpx;
						padding-left: 20rpx;
						display: flex;
						flex-direction: column;
						justify-content: space-between;

						.expir {
							font-size: 24rpx;
							color: $uni-color-grey-dark;
						}
					}

					.btn {
						position: absolute;
						right: 0;
						bottom: 50rpx;
						height: 40rpx;
						padding: 0 10rpx;
						border: 2rpx solid $uni-color-green;
						line-height: 40rpx;
						text-align: center;
						border-radius: 20rpx;
						font-size: 24rpx;
						color: $uni-color-green;
					}
				}
			}
		}

		.footer {
			position: fixed;
			left: 0;
			bottom: $uni-spacing-col-base;
			width: 100%;

			background-color: $uni-color-white;

			.btn_box {
				padding: 10rpx;

				.container {
					padding: 0 $uni-spacing-row-base;
					display: flex;
					justify-content: space-around;

					.bth {
						width: 300rpx;
					}
				}
			}
		}
	}

	.time-box {
		margin: 10rpx 0;
		display: flex;
		justify-content: space-around;

		.time-start-box {
			display: flex;
			align-items: center;

			.time-select {
				width: 120rpx;
				display: flex;
				align-items: center;
				border: 1rpx solid #39B19D;
				padding: 2rpx 20rpx;
				border-radius: 10rpx;
				justify-content: space-between;
			}

			.active {
				border-color: #ccc;
			}
		}
	}

	.pay_finish {
		width: 80vw;
		// height: 300rpx;
		border-radius: 15rpx;
		// background-color: skyblue;
		padding: 20rpx 60rpx;
		color: #39B19D;
		border: 1rpx solid #39B19D;
		font-size: 32rpx;
		box-sizing: border-box;

		.price {
			font-weight: 600;
			text-align: center;
			margin-bottom: 30rpx;
		}

		.order_no {
			margin-bottom: 20rpx;
		}

		.back {
			// display: inline-block;
			width: 100rpx;
			padding: 10rpx 30rpx;
			background-color: #39B19D;
			color: #fff;
			border-radius: 15rpx;
			margin: 40rpx auto 20rpx;
			text-align: center;
		}
	}

	.room_pack_title {
		background-color: #ff914d;
		color: #000;
		padding: 2rpx;
		border-radius: 5rpx;
		text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;

		image {
			width: 30rpx;
		}
	}

	.room_pack_list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		background-color: #fff;
		margin: 10rpx 0;

		.room_pack_list_item {
			width: 48%;
			border: 1rpx solid #ccc;
			border-radius: 10rpx;
			display: flex;
			justify-content: space-between;
			margin-bottom: 10rpx;
			padding: 5rpx 0;
		}

		.active {
			background-color: #c8f0dc;
			color: #ff914d;
		}
	}
</style>